package com.mentaleye.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.open.client.api.model.corp.CorpUserDetail;
import com.dingtalk.open.client.api.service.corp.CorpUserService;
import com.mentaleye.bean.CommonResult;
import com.mentaleye.dal.model.Owner;
import com.mentaleye.service.OwnerService;
import com.mentaleye.service.dingding.helper.AuthHelper;
import com.mentaleye.service.dingding.helper.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/owner")
public class OwnerWebController {
	@Autowired
	private OwnerService ownerService;
	@Autowired
	private CorpUserService corpUserService;

	@RequestMapping("/info")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("dingding/vm/userIndex");
		view.addObject("ddConfig", AuthHelper.getConfig(request));
		return view;
	}

	@RequestMapping("/userInfo")
	@ResponseBody
	public ModelAndView userInfo(@RequestParam(required = false) String code,
			@CookieValue(value = "wuyeUserNo", defaultValue = "") String wuyeUserNo, HttpServletResponse response) {
		CorpUserDetail user = null;
		CommonResult result = null;
		if (StringUtils.isEmpty(wuyeUserNo)) {
			try {
				JSONObject object = UserHelper.gettUserInfo(AuthHelper.getAccessToken(), code);
				user = corpUserService.getCorpUser(AuthHelper.getAccessToken(), object.getString("userid"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (user != null) {
				result = ownerService.queryOwner(null, user.getMobile());
			}
		} else {
			result = ownerService.queryOwner(wuyeUserNo, null);
		}
		ModelAndView view = new ModelAndView("dingding/vm/userShow");

		if (result != null && result.getIsSuccess()) {
			Owner owner = (Owner) result.getData();
			if (owner != null) {
				view.addObject("ownerView", owner);
				if (StringUtils.isEmpty(wuyeUserNo)) {
					Cookie c1 = new Cookie("wuyeUserNo", owner.getUserNo());
					response.addCookie(c1);
				}
			}
		}
		return view;
	}

}
